package com.chl.chart;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;

import org.apache.poi.util.StringUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * https://echarts.apache.org/examples/zh/editor.html?c=sankey-energy&lang=js
 * @author 006006
 *
 */
public class SankeyChart {

	public static void main(String[] args) {
		
		
		HashMap<String,String> name = AppName.getAppName();
		

		//按照小时计算
		String filePath = System.getProperty("user.dir") + "//src//com//chl//chart//20250804-data.json";

		StringBuilder content = new StringBuilder(16);
		try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
			String line;
			while ((line = reader.readLine()) != null) {
				content.append(line);
			}
		} catch (IOException e) {
			System.err.println("读取文件出错：" + e.getMessage());
			return;
		}
		
		String contentStr = content.toString();
		
		
		for(Entry<String,String> entry :name.entrySet()) {
			contentStr = contentStr.replace(entry.getKey(), entry.getValue());
		}
		
		// 使用 Fastjson 解析 JSON 字符串
		JSONObject jsonObject = JSON.parseObject(contentStr);

		JSONArray jsonArray = jsonObject.getJSONArray("nodes");
		JSONArray edgesArray = jsonObject.getJSONArray("edges");

		JSONObject sankey = new JSONObject();
		JSONArray nodes = new JSONArray();
		JSONArray links = new JSONArray();

		
		//排除的集合对象
		ArrayList<String> als = new ArrayList<String>();

		for (int i = 0; i < jsonArray.size(); i++) {
			JSONObject data = jsonArray.getJSONObject(i);
			String id = data.getString("id");
			String type = data.getJSONObject("data").getString("requests");
			String label = data.getString("label");
			JSONObject obj = new JSONObject();
			
			if (id.indexOf("##") > 0) {
				continue;
			}

			try {
				if(StringUtil.isNotBlank(label) && label.indexOf("prod-") < 0){
					als.add(id);
					continue;
				}
			}catch(Exception e) {
				System.out.println(label);
			}
			
//			if (Integer.parseInt(type) < 20000) {
//				als.add(id);
//				continue;
//			}

//			if (nodes.size() > 60) {
//				als.add(id);
//				continue;
//			}

			obj.put("name", id);
			nodes.add(obj);
		}
		
		
		HashMap<String,Integer> ABBA = new HashMap<String,Integer>();

		for (int i = 0; i < edgesArray.size(); i++) {
			JSONObject data = edgesArray.getJSONObject(i);
			String source = data.getString("source");
			String target = data.getString("target");
			int value = Integer.parseInt(data.getJSONObject("data").getString("requests"));

			JSONObject obj = new JSONObject();
			obj.put("source", source);
			obj.put("target", target);
			obj.put("value", value);

			
			//过滤中间件
			if (source.indexOf("##") > 0 || target.indexOf("##") > 0) {
				continue;
			}
			
			//达到排除case则过滤
			if (als.contains(source) || als.contains(target)) {
				continue;
			}
			
			//自身对自身，需要排除掉
			if(source.equals(target)) {
				continue;
//		        boolean bool = checkKeys(links, i, source);
//		        if(bool) {
//		        }
			}
			// A+B形式是首次插入，需要判断 B+A 形式
			String ABBA_key = target + source;
			if(ABBA.containsKey(ABBA_key)) {
				int key_value = ABBA.get(ABBA_key);
				//如果 A -> B的值 小于  B -> A的值， 则取后者
				if(key_value > value) {
					continue;
				}else {
					for (int m = 0; m < links.size(); m++) {
					    JSONObject check = links.getJSONObject(m);
					    if(check.getString("source").equals(target) && check.getString("source").equals(target)) {
					    	links.remove(check);
					    }
					}
				}
			}
			
			
			
//			// B+A形式
//			ABBA_key = target + source;
//			if(ABBA.containsKey(ABBA_key)) {
//				int key_value = ABBA.get(ABBA_key);
//				//如果 A -> B的值 大于  B -> A的值， 则取前者
//				if(key_value > value) {
//					continue;
//				}
//			}
			
			links.add(obj);
			ABBA.put(source+target, value);
			
		}
		sankey.put("nodes", nodes);
		
		RemoveCycleEdge remover = new RemoveCycleEdge();
        JSONArray cleaned = remover.removeAllCycles(links);
		
		sankey.put("links", cleaned);
		writeContent(sankey.toJSONString());
	}

//	/**
//	 * 检查key值是否存在
//	 * @param links
//	 * @param i
//	 * @param source
//	 * @return
//	 */
//	private static boolean checkKeys(JSONArray links, int i, String source) {
//		for (int j = 0; j < links.size(); j++) {
//		    JSONObject check = links.getJSONObject(j);
//		    if (check.containsKey(source)) {
//		    	return true;
//		    }
//		}
//		return false;
//	}

	/**
	 * 写入文档
	 * @param content
	 */
	private static void writeContent(String content) {
		String filePath = System.getProperty("user.dir") + "//src//com//chl//chart//res.txt";
		try {
			Files.write(Paths.get(filePath), content.getBytes(StandardCharsets.UTF_8));
			System.out.println("文件写入成功！");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
